package com.example.seakdreamandroid.whiteNoise;




import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.seakdreamandroid.Constant;
import com.example.seakdreamandroid.MainActivity;
import com.example.seakdreamandroid.R;
import com.example.seakdreamandroid.entity.AudioInfo;
import com.example.seakdreamandroid.entity.User;
import com.example.seakdreamandroid.whiteNoisePlayer.WhiteNoisePlayerActivity;
import com.example.seakdreamandroid.whiteNoisePlayer.WhiteNoisePlayerService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/*
杨锐涵 白噪音的自由组合界面
 */

public class FreeConbination extends Fragment{
    private Context mContext;
    private ArrayList<AudioInfo> channels;
    private WhiteNoiseFreeConbinationChannelAdapter channelAdapter;
    private int idx;
    private int IDX_COUNT = 1;
    private ImageView whiteNoiseImage1,whiteNoiseImage2,whiteNoiseImage3;
    private TextView whiteNoiseName1,whiteNoiseName2,whiteNoiseName3;
    private ImageButton playButton;
    private ImageView pullUp;
//    private Queue<Integer> queue = new LinkedList<Integer>();
//    private Queue<AudioInfo> history = new LinkedList<AudioInfo>();
    private User user;
    private RequestOptions requestOptions = new RequestOptions();
    private WhiteNoisePlayerService.WhiteNoiseControl controller;

    public FreeConbination(){}
    public FreeConbination(Context mContext) {
        this.mContext = mContext;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //获取布局文件
        View view = inflater.inflate(R.layout.layout_whitenoise_fragment_gridview,container,false);
        WhiteNoisePlayerService.registerForListener(handler);
        //获取布局文件中的控件对象
        GridView gridView = view.findViewById(R.id.white_noise_fragment_gridview);
        //给控件对象设置必要的属性
        //给某些控件对象添加事件监听器
        //获取Channel数据源
        channels = setDate();
        //实例化适配器对象
        channelAdapter = new WhiteNoiseFreeConbinationChannelAdapter(
                mContext,
                channels
        );
        controller = WhiteNoisePlayerService.getController();
        user = (User) getActivity().getApplication();
        init(view);
        gridView.setAdapter(channelAdapter);
        gridView.setOnItemClickListener(
                new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if (channels.get(position).getIfVip().equals("1") && !user.getIf_vip().equals("1")) {
                            Toast.makeText(getActivity(), "请充值vip", Toast.LENGTH_SHORT).show();
                        }else {
                            //判断queue中postion的数量
                            List<AudioInfo> audioInfos = WhiteNoisePlayerService.getAudioInfos();
                            if(audioInfos.size() < 3){
                                audioInfos.add(channels.get(position));
                            }else{
                                audioInfos.remove(0);
                                audioInfos.add(channels.get(position));
                            }
                            idx = position;
                            //日志显示被点击的信息
                            //首先获取点击对象
                            AudioInfo c = channels.get(position);
                            //其次日志显示获取到的对象
                            Log.i(FreeConbination.class.getName(),"点击的白噪音：" + c.toString() + "，position：" + position);
                            controller.play(audioInfos,"FreeCombination",null,true);
                            if(IDX_COUNT % 3 == 1){

                                IDX_COUNT++;
                                Glide.with(mContext)
                                        .load(c.getAudioPic())
                                        .apply(requestOptions)
                                        .into(whiteNoiseImage1);

                                whiteNoiseName1.setText(c.getAudioName());

                            }else if(IDX_COUNT % 3 == 2){
                                IDX_COUNT++;
                                Glide.with(mContext)
                                        .load(c.getAudioPic())
                                        .apply(requestOptions)
                                        .into(whiteNoiseImage2);

                                whiteNoiseName2.setText(c.getAudioName());
                            }else{
                                IDX_COUNT++;
                                Glide.with(mContext)
                                        .load(c.getAudioPic())
                                        .apply(requestOptions)
                                        .into(whiteNoiseImage3);

                                whiteNoiseName3.setText(c.getAudioName());
                            }
                        }
                    }
                }
        );

        setHistory();
        setListener();
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        WhiteNoisePlayerService.removeForListener(handler);
    }

    private void setHistory() {
        List<AudioInfo> whiteHistory = WhiteNoisePlayerService.getAudioInfos();
        for(int i = 0;whiteHistory != null && i<whiteHistory.size();i++){

            AudioInfo c = whiteHistory.get(i);
            if(i == 0){
                Glide.with(mContext)
                        .load(c.getAudioPic())
                        .apply(requestOptions)
                        .into(whiteNoiseImage1);

                whiteNoiseName1.setText(c.getAudioName());
            }else if(i == 1){
                Glide.with(mContext)
                        .load(c.getAudioPic())
                        .apply(requestOptions)
                        .into(whiteNoiseImage2);

                whiteNoiseName2.setText(c.getAudioName());
            }else{
                Glide.with(mContext)
                        .load(c.getAudioPic())
                        .apply(requestOptions)
                        .into(whiteNoiseImage3);

                whiteNoiseName3.setText(c.getAudioName());
            }

        }




    }

    private void setListener(){
        MyListener myListener = new MyListener();
        playButton.setOnClickListener(myListener);
        pullUp.setOnClickListener(myListener);
    }

    private class MyListener implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.white_noise_play_button:
                    //判断背景图片与所设图片是否相等
                    switch(WhiteNoisePlayerService.getPlayState()){
                        case WhiteNoisePlayerService.PLAYING:
                            controller.pausePlay(true);
                            break;
                        case WhiteNoisePlayerService.PAUSE:
                            controller.continuePlay(true);
                            break;
                        case WhiteNoisePlayerService.NONE:
                            Toast.makeText(getActivity(),"没有要播放的白噪音组合，挑选几个吧",Toast.LENGTH_LONG).show();;
                            break;
                        case WhiteNoisePlayerService.PREPARING:
                            Toast.makeText(getActivity(),"正在加载中，请稍等",Toast.LENGTH_LONG).show();
                            break;
                    }
                    break;
                case R.id.white_noise_pullup:
                    Intent intent = new Intent(getActivity(), WhiteNoisePlayerActivity.class);
                    startActivity(intent);
                    break;
            }


        }
    }


    //handler机制，可以理解为线程间的通信，我获取到一个信息，然后把这个信息告诉你，就这么简单
    public Handler handler = new Handler(Looper.getMainLooper()) {//创建消息处理器对象
        //在主线程中处理从子线程发送过来的消息

        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case WhiteNoisePlayerService.START_EVENT:
                    //开始播放事件
                    whiteNoiseImage1.setBackground(null);
                    whiteNoiseImage2.setBackground(null);
                    whiteNoiseImage1.setBackground(null);
                    whiteNoiseName1.setText("");
                    whiteNoiseName2.setText("");
                    whiteNoiseName3.setText("");
                    List<AudioInfo> audioInfos = WhiteNoisePlayerService.getAudioInfos();
                    if(audioInfos.size() >= 1){
                        Glide.with(mContext)
                                .load(audioInfos.get(0).getAudioPic())
                                .apply(requestOptions)
                                .into(whiteNoiseImage1);
                        whiteNoiseName1.setText(audioInfos.get(0).getAudioName());
                    }
                    if(audioInfos.size() >= 2){
                        Glide.with(mContext)
                                .load(audioInfos.get(1).getAudioPic())
                                .apply(requestOptions)
                                .into(whiteNoiseImage2);
                        whiteNoiseName2.setText(audioInfos.get(1).getAudioName());
                    }
                    if(audioInfos.size() >= 3){
                        Glide.with(mContext)
                                .load(audioInfos.get(2).getAudioPic())
                                .apply(requestOptions)
                                .into(whiteNoiseImage3);
                        whiteNoiseName3.setText(audioInfos.get(2).getAudioName());
                    }
                case WhiteNoisePlayerService.PAUSE_EVENT:
                    //暂停播放事件
                    playButton.setBackgroundResource(R.mipmap.play);
                    break;
                case WhiteNoisePlayerService.PREPARED_EVENT:
                    //准备完成事件
                case WhiteNoisePlayerService.CONTINUE_EVENT:
                    //继续播放事件
                    playButton.setBackgroundResource(R.mipmap.play2);
                    break;
                case WhiteNoisePlayerService.ERROR_EVENT:
                    playButton.setBackgroundResource(R.mipmap.play);
                    Toast.makeText(getActivity(),"播放器出错了，啥错我不知道",Toast.LENGTH_LONG).show();
                    break;
                case 5:
                    channelAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };
    private void init(View view){
        whiteNoiseImage1 = view.findViewById(R.id.white_noise_image1);
        whiteNoiseImage2 = view.findViewById(R.id.white_noise_image2);
        whiteNoiseImage3 = view.findViewById(R.id.white_noise_image3);
        whiteNoiseName1 = view.findViewById(R.id.white_noise_name1);
        whiteNoiseName2 = view.findViewById(R.id.white_noise_name2);
        whiteNoiseName3 = view.findViewById(R.id.white_noise_name3);
        playButton = view.findViewById(R.id.white_noise_play_button);
        pullUp = view.findViewById(R.id.white_noise_pullup);
        user = (User) getActivity().getApplication();
        if(WhiteNoisePlayerService.getPlayState() == WhiteNoisePlayerService.PLAYING){
                playButton.setBackgroundResource(R.mipmap.play2);
        }else{
            playButton.setBackgroundResource(R.mipmap.play);
        }
    }



    private ArrayList<AudioInfo> setDate() {
        ArrayList<AudioInfo> mlist = new ArrayList<>();

        String URL = Constant.BASE_URL +  "WhiteNoise/FreeConbination/findAllFreeConbination/whiteNoise";
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(URL)

                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e("onFailure","请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String responseBody = response.body().string();
                Gson gson = new Gson();
                Type type= new TypeToken<List<AudioInfo>>(){}.getType();
                List<AudioInfo> audioInfos = gson.fromJson(responseBody,type);
                Log.e("dd",audioInfos.get(0).getIfVip());
                Message message = new Message();
                message.what = 5;
                mlist.addAll(0,audioInfos);
                handler.sendMessage(message);

            }
        });
        return mlist;
    }
}
